package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义订单定时器
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    //处理支付超时订单
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
            Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.selectByStatus(status,time);

        if (ordersList != null && ordersList.size() >0){
            for (Orders orders : ordersList) {
                    orders.setStatus(Orders.CANCELLED);
                    orders.setCancelTime(LocalDateTime.now());
                    orders.setCancelReason("订单支付超时，自动取消");
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                    orderMapper.update(orderVO);
            }
        }

    }

    //处理派送中实际已完成订单
    @Scheduled(cron = "0 0 1 * * ? ")//每天1点处理前一天的派送中订单
        public void processDeliveryOrder(){
            Integer status = Orders.DELIVERY_IN_PROGRESS;
            LocalDateTime time = LocalDateTime.now().plusHours(-1);
            List<Orders> ordersList = orderMapper.selectByStatus(status,time);

            if (ordersList != null && ordersList.size() >0){
                for (Orders orders : ordersList) {
                    orders.setStatus(Orders.COMPLETED);
                    OrderVO orderVO = new OrderVO();
                    BeanUtils.copyProperties(orders,orderVO);
                    orderMapper.update(orderVO);
                }
            }
        }

}
